package com.hmall.controller;

import com.hmall.item.service.IItemService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 长夜漫漫，代码相伴
 * @date 2022/6/20
 */
@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private IItemService itemService;

    @GetMapping("/suggestion")
    public List<String> suggestion(String key){
        try {
//        准备request
            SearchRequest request = new SearchRequest("hm");
//        准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                    SuggestBuilders.completionSuggestion("suggestion").prefix(key).skipDuplicates(true).size(10)
            ));

//        发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //解析结果
            Suggest suggest = response.getSuggest();

            //根据补全查询名称
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");

            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }

            return list;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
